// 音频播放器工具类
export class AudioPlayerUtil {
  constructor() {
    this.audio = null;
    this.isMainPlaying = false;
    this.volume = 50;
    this.speed = 1.0;
    this.currentTime = '00:00';
    this.duration = '00:00';
    this.audioProgress = 0;
    this.audioUrl = '';
  }

  // 初始化音频实例
  initAudioPlayer() {
    if (!this.audio) {
      this.audio = new Audio();
      this.audio.preload = 'auto';
      this.setVolume(this.volume);
      this.setPlaybackRate(this.speed);
      this.setupEventListeners();
    }
    return this.audio;
  }

  // 设置音频源
  setAudioSource(url) {
    this.initAudioPlayer();
    this.audio.src = url;
  }

  // 设置音量
  setVolume(volume) {
    this.volume = volume;
    if (this.audio) {
      this.audio.volume = volume / 100;
    }
  }

  // 设置播放速度
  setPlaybackRate(speed) {
    this.speed = speed;
    if (this.audio) {
      this.audio.playbackRate = speed;
    }
  }

  // 播放音频
  async play() {
    if (this.audio) {
      try {
        await this.audio.play();
        this.isMainPlaying = true;
      } catch (error) {
        console.error('播放失败:', error);
        throw error;
      }
    }
  }

  // 暂停音频
  pause() {
    if (this.audio) {
      this.audio.pause();
      this.isMainPlaying = false;
    }
  }

  // 设置事件监听器
  setupEventListeners() {
    // 加载元数据事件
    this.audio.addEventListener('loadedmetadata', () => {
      this.duration = this.formatTime(this.audio.duration);
      this.currentTime = '00:00';
    });

    // 时间更新事件
    this.audio.addEventListener('timeupdate', () => {
      this.currentTime = this.formatTime(this.audio.currentTime);
      this.audioProgress = (this.audio.currentTime / this.audio.duration) * 100;
    });

    // 播放结束事件
    this.audio.addEventListener('ended', () => {
      this.isMainPlaying = false;
      this.currentTime = '00:00';
      this.audioProgress = 0;
    });
  }

  // 格式化时间
  formatTime(time) {
    if (!time || isNaN(time)) return '00:00';
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }

  // 清理资源
  destroy() {
    if (this.audio) {
      this.audio.pause();
      this.audio = null;
    }
    this.isPlaying = false;
    this.currentPlayingId = null;
  }
}

// 创建单例实例
const audioPlayerUtil = new AudioPlayerUtil();
export default audioPlayerUtil;